package com.masz.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;

/**
 * @author masz
 * @Date 2022/2/2 22:59
 */
@Component
public class RibbonFilterModRequestUri extends ZuulFilter {


    @Override
    public String filterType() {
        return FilterConstants.ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String uri = request.getRequestURI();
        if (uri.contains("test333")) {
            // 转到新的service
            currentContext.set(FilterConstants.SERVICE_ID_KEY, "service-sms");
            // 转发到新的uri
            currentContext.set(FilterConstants.REQUEST_URI_KEY, "/test/sms-test");
        }

        currentContext.setSendZuulResponse(false);



        if (uri.contains("test444")) {
            // 这个配置可以从配置文件中读取，也可以从数据库中读取
            try {
                currentContext.setRouteHost(new URL("http://localhost:8001/test/sms-test"));
            } catch (Exception e) {
            }
        }
        return null;
    }
}
